﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.IO;
using System.Configuration;

using ECCIT;
using ECCIT.Extension.Weibo_v2.Model;
using ECCIT.Extension.Weibo_v2.Common;
using ECCIT.Web;
using OgilvyOne.BLL;
using OgilvyOne.Model;
using OgilvyOne.UKNow.Model;
using OgilvyOne.UKNow.BLL;
using OgilvyOne.UKNow.Configuration;
using OgilvyOne.UKNow.Mobile.Utilities;

namespace OgilvyOne.UKNow.Mobile.APIs.User
{
    public class Register : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            string userName = context.Request["username"];
            string password = context.Request["password"];
            string email = context.Request["email"];
            string mobile = context.Request["mobile"];
            string city = context.Request["city"];
           // string province = context.Request.QueryString["province"];
            string birthday = context.Request["birthday"];

            Stream stream = context.Request.InputStream;
            string interests = context.Request["interests"];
            string token = context.Request["token"] ?? string.Empty;
            if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(password) && !string.IsNullOrEmpty(email))
            {
                MemberBLL mb = new MemberBLL(2052);
                if(mb.EmailIsExists(email))
                {
                    context.Response.Write(ResultUtility.ReturnResultJson("-202", "", "注册失败,邮箱已存在"));
                    return;
                }
                if(mb.UserNameIsExists(userName))
                {
                    context.Response.Write(ResultUtility.ReturnResultJson("-203", "", "注册失败,用户名已存在"));
                    return;
                }

                ResultInfo resinfo = Regs(userName, password, email, mobile, city, birthday, stream, interests, context,
                                          ConfigurationManager.AppSettings["UploadFiles"],token);
                if (resinfo.Result)
                {
                    context.Response.Write(toJson(resinfo.ReturnObject as MemberModel,city));
                }
                else
                {
                    context.Response.Write(ResultUtility.ReturnResultJson("-200", "", "注册失败"));
                }
            }
            else
            {
                context.Response.Write(ResultUtility.ReturnResultJson("-201", "", "注册失败"));
            }
        }

        public bool IsReusable
        {
            get { return true; }
        }

        private ResultInfo Regs(string usr, string pass, string email, string mobile, string city, string birthday, Stream st, string interests, HttpContext htc, string path, string token)
        {
            MemberModel mm = new MemberModel();
            mm.Name = usr;
            mm.Email = email;
            mm.Password = ECCIT.Security.MD5Crypto.GetMD5Hash(pass);
            mm.Mobile = mobile;
            mm.Birthday = birthday;
            int icity = 0;
            if (int.TryParse(city,out icity))
            {
                mm.City = city;
                DictionaryManageModel manageModel = new DictionaryManageBLL().selectDictionary(icity);
                if(manageModel!=null)
                {
                    mm.Provice = manageModel.Upid.ToString();
                }
            }
            // mm.Provice = province;
            mm.LanguageID = 2052;
            mm.InsertTime = DateTime.Now;
            mm.LastLoginTime = DateTime.Now;
            mm.AppToken = token;
            
            mm.MemberImg = SaveImage(htc);
            //if (st.Length!=0)
            //{
            //    mm.MemberImg = saveImg(st, htc, path);
            //}
          
            MemberBLL mb = new MemberBLL(Convert.ToInt32(mm.LanguageID));
            ECCIT.ResultInfo rs = mb.Save(mm);
           
            int? artid = (rs.ReturnObject as MemberModel).ID;

            if (!string.IsNullOrEmpty(interests))
            {
                string artlist = interests;
                string[] artArr = artlist.Substring(0).Split(',');
                MemberIntersetsMappingBLL mimbll = new MemberIntersetsMappingBLL(Convert.ToInt32(mm.LanguageID));
                MemberIntersetsMappingModel mimm = null;
                List<MemberIntersetsMappingModel> lmm = new List<MemberIntersetsMappingModel>();
                foreach (string art in artArr)
                {
                    if (art != "")
                    {
                        mimm = new MemberIntersetsMappingModel();
                        mimm.CreateTime = DateTime.Now.ToShortDateString();
                        mimm.COL_MEMBER_ID = Convert.ToInt32(artid);
                        mimm.COL_INTERESTS_ID = int.Parse(art);
                        lmm.Add(mimm);
                    }
                }
                new MemberIntersetsMappingBLL(2052).Save(lmm);
            }
            return rs;
        }

        private string toJson(MemberModel mem,string idcity)
        {
            UserInfo usinfo = new UserInfo();
            usinfo.ID = int.Parse(mem.ID.ToString());
            usinfo.Name = mem.Name;
            usinfo.AvatarLarge = ConfigCacheManager.DomainName +
                ConfigCacheManager.FilePath.GetFrontImageVirtualPath(string.IsNullOrEmpty(mem.MemberImg)?"phone.jpg":mem.MemberImg);
            usinfo.cityid = string.IsNullOrEmpty(idcity) ? 0 : Convert.ToInt32(idcity);           

            if (!string.IsNullOrEmpty(idcity))
            {
                var bll = new DictionaryManageBLL();
                if (Convert.ToInt32(idcity)== 0)
                {
                    usinfo.City = "所有城市";
                }
                else
                {
                    DictionaryManageModel model = bll.selectDictionary(Convert.ToInt32(idcity));
                    usinfo.City = model.Cnname;
                }
                
            }
            else
            {
                usinfo.City = string.Empty;
            }

            string s=JsonSerializationHelper.ObjectToJson(usinfo);
            return ResultUtility.ReturnResultJson("0", s, "注册成功");

           
        }

        private string SaveImage(HttpContext context)
        {
            try
            {
                HttpPostedFile file = context.Request.Files["avatar"];
                if (file == null) return string.Empty;

                ResultInfo result = UploadedFile.Save(file, ConfigCacheManager.FilePath.UploadFrontImagePath, UploadedFile.RenameHandlers.RenameToGuid);
                if (result.Result)
                {
                    return ((FileInfo)result.ReturnObject).Name;
                }
                else
                {
                    if (result.Exception != null)
                        throw result.Exception;
                    return null;
                }
            }
            catch (Exception ex)
            {
                throw new Exception("用户头像图片时发生异常。错误信息：" + ex.Message);
            }
        }
       

        

        //private string saveImg(Stream stream,HttpContext htc,string path)
        //{
        //    long length = stream.Length;
        //    byte[] buffer = new byte[length];
        //    int readCount = stream.Read(buffer, 0, Convert.ToInt32(length));
            
        //    string imageName =  Guid.NewGuid().ToString() + ".jpg";
        //    string vpath = path + imageName;
        //    string fileName =htc.Server.MapPath(vpath);
        //    FileStream pFileStream = null;
        //    try
        //    {
        //        pFileStream = new FileStream(fileName, FileMode.OpenOrCreate);
        //        pFileStream.Write(buffer, 0, readCount);
        //        return imageName;
        //    }
        //    catch (Exception )
        //    {
        //        return null;
        //    }
        //    finally
        //    {
        //        if (pFileStream != null)
        //            pFileStream.Close();
        //    }
        //}
    }
}
